# this functions is for a returnslist
# to feed with data use returnslist <- getCSPGroupReturn("METALS")
meanSdDf <- function (returnslist, day=5, threshold=0) {
  dflength <- length(returnslist)
  df <-data.frame(pattern=character(dflength), mean=numeric(dflength), sd=numeric(dflength), stringsAsFactors = FALSE)
  j <- 0
  for (i in 1:length(returnslist)) {
    if (dim(returnslist[[i]])[1] >= threshold) { # omit returns with very few observations
      cmean<-colMeans(returnslist[[i]][day])*100
      csd<-colSd(returnslist[[i]][day])*100
      j<-j+1
      df[j,] <- data.frame(pattern=names(returnslist)[i], mean=cmean, sd=csd, stringsAsFactors = FALSE)
    }
  }
  return(df[1:j,])
}

meanSdDiagram <- function (df) {
  if('package:ggplot2' %in% search() || require('ggplot2',quietly=TRUE)) {}
  # now plot the diagram
  p <- ggplot(data=df, 
      aes(x=sd, y=mean, label=pattern)) + coord_cartesian(xlim=c(0,10)) + scale_x_continuous(limits = c(0, 10)) 
  p +  geom_point(aes(colour=pattern)) + 
    geom_text(aes(colou=pattern), size=3, hjust=0, vjust=0) +
    geom_hline(yintercept=0) +
    geom_vline(xintercept=0) +
    opts(legend.position = "none")
}

# method can be mean, ratio or both for mean and ratio optimization
meanSdDiagramLimits <- function (group, method="both", top=10) {
  if('package:ggplot2' %in% search() || require('ggplot2',quietly=TRUE)) {}
  fill_DF <- function(thisdf, method) {
    for (i in 1:dim(thisdf)[1]) {
      DF[count,"method"] <<- method
      DF[count,"pattern"] <<- rownames(thisdf[i,])
      DF[count,"Mean"] <<- thisdf[i,"Mean"]
      DF[count,"DDev"] <<- thisdf[i,"DDev"]
      count <<- count +1
    }
  }
  count <- 1
  dfmean <- data.frame()
  dfratio <- data.frame()
  if (method=="both" | method=="mean") {
    dfmean <- getTopStopLogicPatterns(group, optimize="mean", top=top)
  } 
  if (method=="both" | method=="ratio") {
    dfratio <- getTopStopLogicPatterns(group, optimize="ratio", top=top)    
  }
  mat <- matrix(nrow=dim(dfmean)[1]+dim(dfratio)[1], ncol=4)
  DF <- as.data.frame(mat)
  colnames (DF) <- c("method", "pattern", "Mean", "DDev")
  # now fill DF with contents
  if (dim(dfmean)[1] > 0) fill_DF(dfmean, "A")
  if (dim(dfratio)[1] > 0) fill_DF(dfratio, "C")
  
  # now that DF is filled with data, plot the diagram
  p <- ggplot(data=DF, aes(x=DDev, y=Mean, label=pattern)) + 
    coord_cartesian(xlim=c(0,10)) + 
    scale_x_continuous(limits = c(0, 10)) +
    opts(title=group) + 
    opts(plot.title = theme_text(size=24, lineheight=.8, face="bold"))
  p + geom_point(aes(size=4)) + 
    geom_text(aes(colour=method), size=5, hjust=-0.05, vjust=0.5) +
    geom_hline(yintercept=0) +
    geom_vline(xintercept=0) +
    opts(legend.position = "none")
  #return (DF)
}



